//
//  BaseViewController.swift
//  readtool
//
//  Created by luoyangguang on 16/11/23.
//  Copyright © 2016年 DAD. All rights reserved.
//

import UIKit

class IvyDadBaseViewController: UIViewController, UIGestureRecognizerDelegate {

    var gifImage: UIImageView!
    var rightView: UIView!
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

//        self.navigationController?.interactivePopGestureRecognizer?.delegate = self
        self.baseSetupControls()
        self.baseAddNotification()
		
		
		// 侧滑返回
		// 启用系统自带侧滑
		self.navigationController?.interactivePopGestureRecognizer?.delegate = self
		// 自定义方法.有bug，先注释
//		setCustomPop()
    }

    
    fileprivate func baseAddNotification() {
        
//        NotificationCenter.default.addObserver(self, selector: #selector(setupPlayingIconState), name: NSNotification.Name(rawValue: NotificationConst.StopAudioPlayerNotifiaction), object: nil)
    }

    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        self.setupPlayingIconState()
    }
    
    
    func setupPlayingIconState() {
        
        let isAnimation = UserDefaults.standard.bool(forKey: "PLAY_ANIMATION")
        
        if isAnimation {
            
            gifImage.startAnimating()
        } else {
            
            gifImage.stopAnimating()
        }
        
        let isHiddenAnimation = UserDefaults.standard.bool(forKey: "HIDDEN_ANIMATION")
        
        if isHiddenAnimation {
            
            rightView.isHidden = false
        } else {
            
            rightView.isHidden = true
        }
    }

    
    ///设置基本控件
    fileprivate func baseSetupControls() {
        
        let color = UIColor.rgb("84a740", alpha: 0.85)
        self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white, NSFontAttributeName: UIFont.systemFont(ofSize: 18)]
        self.navigationController?.navigationBar.setBackgroundImage(baseImageWithColor(color), for: .default)
        self.automaticallyAdjustsScrollViewInsets = false
        self.navigationController?.navigationBar.isTranslucent = true
        self.setupLeftBarButtonItem()
        self.setupRightBarButtonItem()
    }

    
    ///设置导航栏左侧按钮
    func setupLeftBarButtonItem() {
        
        self.navigationItem.leftBarButtonItem = self.getLeftBarButtonItem()
    }
    
    
    /// 设置导航左边按钮
    func getLeftBarButtonItem() -> UIBarButtonItem {
        
        let leftButton = UIButton.init(type: .custom)
        leftButton.setImage(UIImage.init(named: "nav_back_botton_custom"), for: .normal)
        leftButton.frame = CGRect.init(x: 0, y: 0, width: 22, height: 44)
        leftButton.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 10)
        leftButton.addTarget(self, action: #selector(basePopView), for: .touchUpInside)
        
        return UIBarButtonItem.init(customView: leftButton)
    }
    
    
    ///设置导航栏右侧按钮
    func setupRightBarButtonItem() {
        
        self.navigationItem.rightBarButtonItem = self.getRightBarButtonItem()
    }
    
    
    /// 设置导航右边按钮
    func getRightBarButtonItem() -> UIBarButtonItem {
        
        rightView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: 24, height: 44))
        gifImage = UIImageView.init(frame: CGRect.init(x: 6, y: 12, width: 18, height: 18))
        
        var imageArray = [UIImage]()
        
        for i in 0 ..< 6 {
            
            let image = UIImage.init(named: "player_gif\(i)")
            
            if image != nil {
                
                imageArray.append(image!)
            }
        }
        
        gifImage.image = imageArray.first
        gifImage.animationImages = imageArray
        gifImage.animationDuration = 0.6
        gifImage.highlightedAnimationImages = imageArray
        rightView.addSubview(gifImage)
        
        let rightBtn = UIButton.init(type: .custom)
        rightBtn.frame = CGRect.init(x: 0, y: 0, width: 24, height: 34)
        rightBtn.backgroundColor = UIColor.clear
        rightBtn.addTarget(self, action: #selector(basePresentToAudioPlayerView), for: .touchUpInside)
        rightView.addSubview(rightBtn)
        
        return UIBarButtonItem.init(customView: rightView)
    }
    
    
    ///返回上一页
    func basePopView() {
        
        if self.navigationController != nil && self.navigationController!.childViewControllers.count > 1 {
            
            _ = self.navigationController?.popViewController(animated: true)
        } else {
            
            self.dismiss(animated: true, completion: nil)
        }
    }

    
    /// 跳转到播放器
    func basePresentToAudioPlayerView() {
        
//        // 统计 begin
//        StatTool.addStatistics(StatConst.OpenPlayer)
//        // 统计 end
//        
//        let player = AudioPlayerViewController.shared
//        
//        if player.navigationController != nil {
//            
//            for vc in player.navigationController!.childViewControllers {
//                
//                if vc.self == player.self {
//                    
//                    vc.hidesBottomBarWhenPushed = true
//                    _ = self.navigationController?.popToViewController(vc, animated: true)
//                    return
//                }
//            }
//        }
//        
//        player.hidesBottomBarWhenPushed = true
//        self.navigationController?.pushViewController(player, animated: true)
    }
    
    
    /// 颜色转成图片
    func baseImageWithColor(_ color: UIColor) -> UIImage {
        
        let rect = CGRect.init(x: 0, y: 0, width: 1, height: 1)
        UIGraphicsBeginImageContext(rect.size)
        let context = UIGraphicsGetCurrentContext()
        context!.setFillColor(color.cgColor)
        context!.fill(rect)
        
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        return image!
    }
	
	// MARK: - 自定义侧滑返回功能
	
	private func setCustomPop() {
		
		// 自定义侧滑返回功能
		let target = self.navigationController?.interactivePopGestureRecognizer?.delegate
		// handleNavigationTransition 系统私有API
		let panGR = UIPanGestureRecognizer(target: target, action: Selector(("handleNavigationTransition:")))
		panGR.delegate = self
		self.view.addGestureRecognizer(panGR)
		self.navigationController?.interactivePopGestureRecognizer?.isEnabled = false
	}
	
	internal func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
		if self.navigationController?.childViewControllers.count == 1 {
			return false
		}
		return true
	}
    
}
